import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/expense_model.dart';
import '../providers/expense_providers.dart';
import '../themes/expense_theme.dart';

/// 分类管理界面
class CategoryManagementScreen extends ConsumerWidget {
  const CategoryManagementScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final categoryStats = ref.watch(categoryStatisticsProvider);
    final incomeStats = ref.watch(incomeCategoryStatisticsProvider);
    final expenseStats = ref.watch(expenseCategoryStatisticsProvider);

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: ExpenseTheme.background,
        appBar: AppBar(
          title: const Text('分类管理'),
          backgroundColor: ExpenseTheme.primaryBlue,
          foregroundColor: Colors.white,
          elevation: 0,
          bottom: const TabBar(
            indicatorColor: Colors.white,
            labelColor: Colors.white,
            unselectedLabelColor: Colors.white70,
            tabs: [
              Tab(text: '收入分类'),
              Tab(text: '支出分类'),
            ],
          ),
        ),
        body: TabBarView(
          children: [
            // 收入分类
            _buildCategoryList(
              context,
              ExpenseCategoryExtension.incomeCategories,
              incomeStats,
              ExpenseTheme.incomeGreen,
            ),
            // 支出分类
            _buildCategoryList(
              context,
              ExpenseCategoryExtension.expenseCategories,
              expenseStats,
              ExpenseTheme.expenseRed,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建分类列表
  Widget _buildCategoryList(
    BuildContext context,
    List<ExpenseCategory> categories,
    Map<ExpenseCategory, double> statistics,
    Color themeColor,
  ) {
    // 计算总金额用于百分比计算
    final totalAmount = statistics.values.fold(0.0, (sum, amount) => sum + amount);

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: categories.length,
      itemBuilder: (context, index) {
        final category = categories[index];
        final amount = statistics[category] ?? 0.0;
        final percentage = totalAmount > 0 ? (amount / totalAmount) * 100 : 0.0;

        return Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: _buildCategoryItem(
            context,
            category,
            amount,
            percentage,
            themeColor,
          ),
        );
      },
    );
  }

  /// 构建分类项目
  Widget _buildCategoryItem(
    BuildContext context,
    ExpenseCategory category,
    double amount,
    double percentage,
    Color themeColor,
  ) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: ExpenseTheme.softShadow,
      ),
      child: Column(
        children: [
          Row(
            children: [
              // 分类图标
              Container(
                width: 48.w,
                height: 48.h,
                decoration: BoxDecoration(
                  color: themeColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Center(
                  child: Text(
                    category.icon,
                    style: TextStyle(fontSize: 24.sp),
                  ),
                ),
              ),
              
              SizedBox(width: 16.w),
              
              // 分类信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      category.displayName,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        color: ExpenseTheme.textPrimary,
                      ),
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      '¥${amount.toStringAsFixed(2)}',
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                        color: themeColor,
                      ),
                    ),
                  ],
                ),
              ),
              
              // 百分比
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    '${percentage.toStringAsFixed(1)}%',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: themeColor,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Container(
                    width: 60.w,
                    height: 4.h,
                    decoration: BoxDecoration(
                      color: ExpenseTheme.divider,
                      borderRadius: BorderRadius.circular(2.r),
                    ),
                    child: FractionallySizedBox(
                      alignment: Alignment.centerLeft,
                      widthFactor: percentage / 100,
                      child: Container(
                        decoration: BoxDecoration(
                          color: themeColor,
                          borderRadius: BorderRadius.circular(2.r),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
          
          // 如果有金额，显示详细信息
          if (amount > 0) ...[
            SizedBox(height: 12.h),
            Divider(height: 1.h),
            SizedBox(height: 12.h),
            _buildCategoryDetails(context, category, amount, themeColor),
          ],
        ],
      ),
    );
  }

  /// 构建分类详细信息
  Widget _buildCategoryDetails(
    BuildContext context,
    ExpenseCategory category,
    double amount,
    Color themeColor,
  ) {
    return InkWell(
      onTap: () {
        _showCategoryDetails(context, category, amount, themeColor);
      },
      borderRadius: BorderRadius.circular(8.r),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 12.w),
        decoration: BoxDecoration(
          color: themeColor.withValues(alpha: 0.05),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Row(
          children: [
            Icon(
              Icons.info_outline,
              size: 16.sp,
              color: themeColor,
            ),
            SizedBox(width: 8.w),
            Text(
              '查看详细记录',
              style: TextStyle(
                fontSize: 14.sp,
                color: themeColor,
                fontWeight: FontWeight.w500,
              ),
            ),
            const Spacer(),
            Icon(
              Icons.arrow_forward_ios,
              size: 12.sp,
              color: themeColor,
            ),
          ],
        ),
      ),
    );
  }

  /// 显示分类详细信息
  void _showCategoryDetails(
    BuildContext context,
    ExpenseCategory category,
    double amount,
    Color themeColor,
  ) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.7,
        decoration: BoxDecoration(
          color: ExpenseTheme.background,
          borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
        ),
        child: Column(
          children: [
            // 拖拽指示器
            Container(
              margin: EdgeInsets.only(top: 12.h),
              width: 40.w,
              height: 4.h,
              decoration: BoxDecoration(
                color: ExpenseTheme.divider,
                borderRadius: BorderRadius.circular(2.r),
              ),
            ),
            
            // 标题
            Padding(
              padding: EdgeInsets.all(20.w),
              child: Row(
                children: [
                  Container(
                    width: 40.w,
                    height: 40.h,
                    decoration: BoxDecoration(
                      color: themeColor.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(10.r),
                    ),
                    child: Center(
                      child: Text(
                        category.icon,
                        style: TextStyle(fontSize: 20.sp),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          category.displayName,
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: FontWeight.w600,
                            color: ExpenseTheme.textPrimary,
                          ),
                        ),
                        Text(
                          '总计：¥${amount.toStringAsFixed(2)}',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: themeColor,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                  IconButton(
                    onPressed: () => Navigator.pop(context),
                    icon: Icon(Icons.close, size: 24.sp),
                  ),
                ],
              ),
            ),
            
            Divider(height: 1.h),
            
            // 记录列表
            Expanded(
              child: Consumer(
                builder: (context, ref, child) {
                  final allExpenses = ref.watch(expenseListProvider);
                  final categoryExpenses = allExpenses
                      .where((expense) => expense.category == category)
                      .toList();

                  if (categoryExpenses.isEmpty) {
                    return const Center(
                      child: Text(
                        '暂无记录',
                        style: TextStyle(
                          color: ExpenseTheme.textSecondary,
                          fontSize: 16,
                        ),
                      ),
                    );
                  }

                  return ListView.builder(
                    padding: EdgeInsets.all(16.w),
                    itemCount: categoryExpenses.length,
                    itemBuilder: (context, index) {
                      final expense = categoryExpenses[index];
                      return _buildExpenseItem(expense, themeColor);
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建记账条目
  Widget _buildExpenseItem(ExpenseModel expense, Color themeColor) {
    return Container(
      margin: EdgeInsets.only(bottom: 8.h),
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: ExpenseTheme.divider),
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (expense.description.isNotEmpty)
                  Text(
                    expense.description,
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                      color: ExpenseTheme.textPrimary,
                    ),
                  ),
                SizedBox(height: 4.h),
                Text(
                  '${expense.date.month}月${expense.date.day}日 ${expense.date.hour.toString().padLeft(2, '0')}:${expense.date.minute.toString().padLeft(2, '0')}',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: ExpenseTheme.textSecondary,
                  ),
                ),
              ],
            ),
          ),
          Text(
            '¥${expense.amount.toStringAsFixed(2)}',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: themeColor,
            ),
          ),
        ],
      ),
    );
  }
}
